<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
	function add($data) {
		$this->db->trans_start();
		$this->db->insert('user', $data);
		$insert_id = $this->db->insert_id();
		$this->db->trans_complete();
		log_message('debug', $this->db->last_query());
		
		return $insert_id;
	}
	
	function exists_name($name) {
		$this->db->where('name', $name);
		$this->db->from('user');
		$count = $this->db->count_all_results();
		log_message('debug', $this->db->last_query());
		
		return $count > 0;
	}
	
	function exists_email($email) {
		$this->db->where('email', $email);
		$this->db->from('user');
		$count = $this->db->count_all_results();
		log_message('debug', $this->db->last_query());
		
		return $count > 0;
	}
	
	function get_by_id($user_id) {
		$this->db->where('id', $user_id);
		$this->db->where('status', DB_STATUS_NORMAL);
		$query = $this->db->get('user');
		log_message('debug', $this->db->last_query());
		
		$count = $this->db->count_all_results();
		return $count == 1 ? $query->row_array() : NULL;
	}
	
	function get_by_name_password($name, $password) {
		$this->db->where('name', $name);
		$this->db->where('password', $password);
		$this->db->where('status', DB_STATUS_NORMAL);
		$query = $this->db->get('user');
		log_message('debug', $this->db->last_query());
		
		$count = $this->db->count_all_results();
		return $count == 1 ? $query->row_array() : NULL;
	}
	
	function update_login_info($user_id) {
		$this->db->trans_start();
		$this->db->set('last_login_ip', $this->input->ip_address());
		$this->db->set('last_login_time', date('Y-m-d H:i:s'));
		$this->db->set('login_times', 'login_times+1', FALSE);
		$this->db->where('id', $user_id);
		$this->db->update('user');
		$affected_rows = $this->db->affected_rows();
		$this->db->trans_complete();
		log_message('debug', $this->db->last_query());
		
		return $affected_rows;
	}
	
	function update_password($user_id, $new_password) {
		$this->db->trans_start();
		$this->db->set('password', $new_password);
		$this->db->where('id', $user_id);
		$this->db->update('user');
		$affected_rows = $this->db->affected_rows();
		$this->db->trans_complete();
		log_message('debug', $this->db->last_query());
		
		return $affected_rows;
	}
}